<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

/**
 * 用户模型
 *
 * @author www.dingwei.cn
 */

class DlnUserModel extends MY_Model{
	
	public $tbUser = 'deliveryman';
	public $tbSession = 'deliveryman_session';
	public $tbVerifyCode = 'deliveryman_verify_code';
	public $tbBankCard = 'deliveryman_bank_card';
	public $tbAmountDetails = 'deliveryman_amount_details';
	public $tbMessage = 'deliveryman_message';
	public $tbMessageViewed = 'deliveryman_message_viewed';
	public $tbAuthRemarks = 'deliveryman_auth_remarks';

	/**
	 * 获取手机验证码
	 * @param 	string $mobile
	 * @param 	string $code
	 * @return	array
	 */
	public function getSmsCodeLogInfo($mobile, $code = ''){
		
		$this->db->select('code,addtime')
				 ->where('mobile', $mobile);
		if($code){
			$this->db->where('code', $code);
		}
		return $this->getOne($this->tbVerifyCode);
	}
	
	/**
	 * 判断电话号码是否存在
	 *
	 * @param	string	$mobile	//手机号码
	 * @return	boolean (false:不存在   true:存在)
	 */
	public function mobileIsExist($mobile, $notId = 0){
			
		if( ! $mobile) return false;
		$this->db->select('id')->where(array('mobile' => $mobile));
		if($notId){
			$this->db->where(array('id <>' => $notId));
		}
        $this->db->where(array('status >' => 0));
		$tA = $this->getOne($this->tbUser);
		if($tA){
			return $tA['id'];
		}
			
		return false;
	}
	
    /**
     * 获取消费者信息
     * @param $consumerIds 消费者ids
     * @return array
     * @author zyl
     */
    public function getInfoByIds($consumerIds, $countyId = []){
    	
    	if( ! $consumerIds){
    		return array();
    	}
    	
    	$this->db
	    	->select('id,name,jpush_code,province_id,city_id,county_id')
	    	->where_in('id',$consumerIds);
    	
	    if($countyId){
	    	$this->db->where_in('county_id', $countyId);
	    }
    	
    	$tA = $this->getAll($this->tbUser);
    	
    	$tData = array();
    	foreach ($tA as $k=>$v){
//     		$tA[$k]['portrait'] = $v['portrait'] ? getImage($v['portrait']) : getDefaultPortrait(1);
//     		$tA[$k]['balance'] = $v['balance'] ? $v['balance'] : '0.00';
//     		$tA[$k]['integral'] = $v['integral'] ? $v['integral'] : '0';
//     		$tA[$k]['gender'] = $v['gender'] ? $this->getGender($v['gender']) : '保密';
    		$tData[$v['id']] = $v;
    	}
    	
    	return $tData;
    }
    
    /**
     * 获取详情
     * @param $consumerId id
     * @return array
     */
	public function getInfo($id){

		$this->db
			 ->select('id,type,name,portrait,mobile,identity_card,identity_card_img,
                        status,score,order_type,order_total,work_status,
			 		    order_complete_total,order_overtime_total,amount,longitude,
                        latitude,addtime,province_id,city_id,county_id,pay_password')
			 ->where('id', $id);
		$tA = $this->getOne($this->tbUser);
		if($tA){
			$tA['portrait'] = getImage($tA['portrait'], 'xs');
			$tA['identity_card_img'] = $tA['identity_card_img'] ? getImage($tA['identity_card_img'], 'og') : '';
			$tA['score'] = $tA['score'] ? $tA['score'] : 0;
			get_instance()->loadModel('AdmSettingModel', 'mSetting', 'admin');
			$tAA = $this->mSetting->getLocationNameByIds([$tA['province_id'], $tA['city_id'], $tA['county_id']]);
			$tA['province'] = isset($tAA[$tA['province_id']]) ? $tAA[$tA['province_id']]['name'] : '';
			$tA['city'] = isset($tAA[$tA['city_id']]) ? $tAA[$tA['city_id']]['name'] : '';
			$tA['county'] = isset($tAA[$tA['county_id']]) ? $tAA[$tA['county_id']]['name'] : '';

			if( ! $tA['order_type']){
			    get_instance()->loadModel('DlnOrderModel', 'mOrder', 'deliveryman');
			    $tA['order_type'] = array_keys($this->mOrder->type());
			}else{
			    $tA['order_type'] = explode(',', $tA['order_type']);
			}

			if($tA['pay_password']){
			    $tA['pay_password'] = 2;
			}else{
			    $tA['pay_password'] = 1;
			}
		}

		return $tA;
	}
	
	/**
	 * 获取用户信息通过session
	 * 
	 * @param	string 	$sessionid	会话id
	 * @param	integer $type	(1：app 2：pc)
	 * @return	array
	 */
 	public function getInfoBySessionid($sessionid, $type = 1){
 	
 		if( ! $sessionid){
 			return array();
 		}
 		$this->db->select('u.id,u.name,u.mobile,u.status,u.county_id,u.order_type')
 				 ->join($this->tbUser.' u', 'u.id = se.deliveryman_id')
 				 ->where(array('se.sessionid' => $sessionid, 'se.type' => $type));	
 				 
 		$tA = $this->getOne($this->tbSession.' se');
 		if( ! $tA){
 			return array();
 		}
 		
 		if( ! $tA['order_type']){
 		    get_instance()->loadModel('DlnOrderModel', 'mOrder', 'deliveryman');
 		    $tA['order_type'] = array_keys($this->mOrder->type());
 		}else{
 		    $tA['order_type'] = explode(',', $tA['order_type']);
 		}
 		return $tA;
 	} 
 	
 	/**
 	 * 获取用户信息
 	 * 
 	 * @param	string	$mobile		手机号码
 	 * @param	string	$password	密码
     * @return 	array
 	 */
 	public function getInfoByMobileAndPassword($mobile, $password){
 		
 		if( ! $mobile || ! $password){
 			return array();
 		}
 		
 		$this->db->select('id,status,jpush_code,work_status,status')
 				 ->where(['mobile' => $mobile, 'password' => $password, 'status >' => 0]);
 		$tA = $this->getOne($this->tbUser);
 		if(empty($tA)) $tA = array();
 		return $tA;
 	}
 	
 	/**
 	 * 获取账户余额
 	 * @param 	integer $id
 	 * @return	number
 	 */
 	public function getAmount($id){
 	
 		$this->db->select('amount')->where('id', $id);
 		$tA = $this->getOne($this->tbUser);
 		if($tA){
 			return $tA['amount'];
 		}
 		 
 		return 0;
 	}
 	
 	/**
 	 * 获取余额列表状态
 	 * @param number $status
 	 */
 	public function amountDetailsStatus($status = 0){
 		
 		$config = [
 					1 => '申请中',
 					2 => '成功',
 					3 => '拒绝'
 		];
 		
 		if($status){
 			return isset($config[$status]) ? $config[$status] : '';
 		}
 		
 		return $config;
 	}
 	
 	/**
 	 * 获取余额列类型
 	 * @param number $status
 	 */
 	public function amountDetailsType($type = 0){
 		
 		$config = [
 					1 => '配送费收入',
 					2 => '提现',
 					3 => '提现拒绝',
 		];
 		
 		if($type){
 			return isset($config[$type]) ? $config[$type] : '';
 		}
 		
 		return $config;
 	}
 	
 	/**
 	 * 类型
 	 * @param 	integer $type
 	 * @return	mixed
 	 */
 	public function type($type = null){
 		
 		$config = [1 => '普通配送员', 2 => '平台配送员'];
 		if($type){
 			return isset($config[$type]) ? $config[$type] : '';
 		}
 		return $config;
 	}
 	
 	/**
 	 * 获取状态显示样式
 	 * @param 	integer $status
 	 * @return	string
 	 */
 	public function status($status = null, $show = false){
 	
 		$config = [1 => '待认证', 2 => '已通过认证', 3 => '认证失败', 4 => '已停用', 5 => '认证中'];
 		if( ! $status){
 			return $config;
 		}
 	
 		if($status && ! isset($config[$status])){
 			return '';
 		}
 	
 		if( ! $show){
 			return $config[$status];
 		}
 	
 		if($status == 1){
 			return '<span class="label label-default">'.$config[$status].'</span>';
 		}elseif($status == 2){
 			return '<span class="label label-success">'.$config[$status].'</span>';
 		}elseif($status == 3){
 			return '<span class="label label-warning">'.$config[$status].'</span>';
 		}elseif($status == 4){
 			return '<span class="label label-danger">'.$config[$status].'</span>';
 		}elseif($status == 5){
 			return '<span class="label label-info">'.$config[$status].'</span>';
 		}
 	
 		return'';
 	}
 	
 	/**
 	 * 获取配送员区域
 	 * @param 	integer $userId
 	 * @return	array
 	 */
 	public function getRegion($userId){
 		
 		$this->db->select('province_id,city_id,county_id')
 				 ->where('id', $userId);
 		
 		return array_values($this->getOne($this->tbUser));
 	}
 	
 	/**
 	 * 获取最新一条审核备注信息
 	 * @param     integer $userId
 	 * @return    string
 	 */
 	public function getNewOneAuthRemarks($userId){
 	
 	    $this->db->select('remarks')
 	             ->where('deliveryman_id', $userId)
 	             ->order_by('addtime desc');
 	    $tA = $this->getOne($this->tbAuthRemarks);
 	    
 	    return $tA ? $tA['remarks'] : '';
 	}

    /**
     * 获取配送范围内的配送员
     * @param $latitude
     * @param $longitude
     * @param $distance  距离（m）
     * @return array
     */
 	public function getDlnUser($latitude, $longitude, $distance = 5){

        if(!$latitude || !$longitude){
            return array();
        }
        $select = '(ACOS(SIN(('.$latitude.' * 3.1415) / 180 )
						*SIN((latitude * 3.1415) / 180 ) + COS(('
            .$latitude.' * 3.1415) / 180 ) * COS((latitude * 3.1415) / 180 ) * COS(('
            .$longitude.' * 3.1415) / 180 - (longitude * 3.1415) / 180 ) ) * 6380 )';

        $this->db->select('id,jpush_code,name,mobile,'.$select.'  as distance,longitude,latitude')
            ->where_in('type', array(1,2))
            ->where('status', 2)
            ->where('work_status', 2)
            ->having('distance <', $distance)
            ->order_by('distance asc')
            ->limit(50);

        $data = $this->getAll($this->tbUser);

        return $data;
    }
}